package org.gdkm.el;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 文件服务类. </br> 
 * 用于减低的程序的耦合性. </br> 
 * 日期: 2012-10-13
 * <p>
 * 
 * @author Arylo<<b>arylo.open@gmail.com</b>>
 * @version 1.0
 */
public class FileServer implements Runnable {
	/**
	 * 扫描文件目录时间, 当前为{@value} 秒
	 */
	public static final int second = 60;
	private static boolean lock = false;

	/**
	 * 构建一个FileServer对象.
	 */
	public FileServer() {
		createDir();
		updateList();
		new Thread(this).start();
		Intent.writeLog("Server", "The FileServer Init Finished.");
	}

	private void createDir() {
		File path = new File(Intent.getFilePath());
		if (path.exists() == false) {
			path.mkdirs();
		}
		for (String _s : Intent.getFilePathList()) {
			File file = new File(_s);
			if (file.exists() == false) {
				file.mkdirs();
			}
		}
	}

	private void findFile(File path, Element root) {
		for (File _f : path.listFiles()) {
			if (_f.isFile() == true) {
				Element elt = root.addElement("File");
				elt.setText(_f.getName());
			}
			if (_f.isDirectory() == true) {
				Element dir = root.addElement("Dir");
				dir.addAttribute("name", _f.getName());
				findFile(_f, dir);
			}
		}
	}

	private void updateList() {
		lock = true;
		Document doc = new DocumentFactory().createDocument();
		Element root = doc.addElement("Root");
		for (String _s : Intent.getFilePathList()) {
			File path = new File(_s);
			Element dir = root.addElement("Path");
			dir.addAttribute("name", path.getName());
			findFile(path, dir);
		}
		OutputFormat format = new OutputFormat("", true, "UTF-8");
		try {
			FileWriter fw = new FileWriter(Intent.getFilePath() + "file.xml");
			XMLWriter writer = new XMLWriter(fw, format);
			writer.write(doc);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			lock = false;
		}
	}

	/**
	 * 返回文件树.
	 * 
	 * @return 一个File 类型.
	 */
	public static File getFileList() {
		if (lock == false) {
			return new File(Intent.getFilePath() + "file.xmil");
		}
		return null;
	}

	/**
	 * FileServer扫描线程.
	 */
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(second * 1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
			updateList();
		}
	}

}